package com.fp.voiceshoper.exp;
 
import java.util.ArrayList;
import java.util.HashMap;  
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.w3c.dom.Text;

import com.fp.voiceshoper.DragNDropListActivity;
import com.fp.voiceshoper.EditItemActivity;
import com.fp.voiceshoper.QuickAction;
import com.fp.fpShoper.R;
import com.fp.voiceshoper.db.DbOpenHelper;
import com.fp.voiceshoper.interfaces.RepeatListener;
import com.fp.voiceshoper.interfaces.RepeatButtonClickListener;
import com.fp.voiceshoper.items.ActionItem;
import com.fp.voiceshoper.items.ShopItemData;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.AnimationUtils;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ExpandableListAdapter;
import android.widget.TextView;
import java.lang.Object;

public class SampleExpandableListAdapter extends BaseExpandableListAdapter implements ExpandableListAdapter  {
	public Context context;
    private LayoutInflater vi;
    public ShopItemData[][] data;
    private ArrayList<String> categorys = new ArrayList<String>();
    int _objInt;
    
    DbOpenHelper dbOpenHelper;
   
    private final int ADD_10=10;
    private final int ADD_100=100;
    private final int ADD_1000=1000;
    
    private final int REM_10=-10;
    private final int REM_100=-100;
    private final int REM_1000=-1000;
    
    private final int REM_ALL=0;
    private final int REM_ITEM=12340;
  
   
    private static final int GROUP_ITEM_RESOURCE = R.layout.group_view;
    private static final int CHILD_ITEM_RESOURCE = R.layout.child_view;
 
    
    public SampleExpandableListAdapter(Context context, Activity activity, ShopItemData[][] data) {
        this.data = data;
        this.context = context;
        vi = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.dbOpenHelper=new DbOpenHelper(context);
        categorys=dbOpenHelper.getFavsCat();
        _objInt = data.length; 
   
    }
  
    public ShopItemData getChild(int groupPosition, int childPosition) {
        return data[groupPosition][childPosition];
    }

    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    public int getChildrenCount(int groupPosition) {
        return data[groupPosition].length;
    }

    private void QuickActionsGrp(View view, final int grp){
    	Drawable remRes=context.getResources().getDrawable(R.drawable.icon_trash);
    	ActionItem remItem 		= new ActionItem(REM_ITEM, context.getString(R.string.action_rem), remRes);
        //use setSticky(true) to disable QuickAction dialog being dismissed after an item is clicked
       
		final QuickAction mQuickAction 	= new QuickAction(context.getApplicationContext(),false);
		mQuickAction.addActionItem(remItem);
		
		
		//setup the action item click listener
				mQuickAction.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
					@Override
					public void onItemClick(QuickAction quickAction, int pos, int actionId) {
						ActionItem actionItem = quickAction.getActionItem(pos);
						
						switch (actionId) {
						case REM_ITEM:
							delGrp(grp);

							break;
						default:
							break;
						}    	
					}
				});
				
				mQuickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
					@Override
					public void onDismiss() {
						
					}
				});
				mQuickAction.show(view);
		
    }
    
    
    
    private void QuickActions(ShopItemData child,View view, final int grp, final int id){
    
    	
		final ShopItemData selected=child;
		final TextView curenView=(TextView)view;
		
		String buy_unbuy=context.getString(R.string.action_buy);
		Drawable buy10Res=context.getResources().getDrawable(R.drawable.add_10);
		Drawable buy100Res=context.getResources().getDrawable(R.drawable.add_100);
		Drawable buy1000Res=context.getResources().getDrawable(R.drawable.add_1000);
		
		
		Drawable rem10Res=context.getResources().getDrawable(R.drawable.rem_10);
		Drawable rem100Res=context.getResources().getDrawable(R.drawable.rem_100);
		Drawable rem1000Res=context.getResources().getDrawable(R.drawable.rem_1000);
		
		Drawable remRes=context.getResources().getDrawable(R.drawable.icon_trash);
		Drawable remitemsRes=context.getResources().getDrawable(R.drawable.icon_eraser);
		
		String[] mystr=context.getResources().getStringArray(R.array.item_type);
		String type=mystr[selected.getType()];

		ActionItem add10Item 		= new ActionItem(ADD_10, type, buy10Res);
		ActionItem add100Item 		= new ActionItem(ADD_100, type, buy100Res);
		ActionItem add1000Item 		= new ActionItem(ADD_1000, type, buy1000Res);
		
		
		ActionItem rem10Item 		= new ActionItem(REM_10, type, rem10Res);
		ActionItem rem100Item 		= new ActionItem(REM_100, type, rem100Res);
		ActionItem rem1000Item 		= new ActionItem(REM_1000, type, rem1000Res);
		
		ActionItem remAllItem 		= new ActionItem(REM_ALL, context.getString(R.string.clear_button), remitemsRes);
		
		ActionItem remItem 		= new ActionItem(REM_ITEM, context.getString(R.string.action_rem), remRes);
        //use setSticky(true) to disable QuickAction dialog being dismissed after an item is clicked
       
        
		final QuickAction mQuickAction 	= new QuickAction(context.getApplicationContext(),true);
	  
		
		mQuickAction.addActionItem(rem10Item);
		mQuickAction.addActionItem(add10Item);
		
		
		mQuickAction.addActionItem(rem100Item);
		mQuickAction.addActionItem(add100Item);
		
		
		mQuickAction.addActionItem(rem1000Item);
		mQuickAction.addActionItem(add1000Item);
		
		mQuickAction.addActionItem(remAllItem);
		
		mQuickAction.addActionItem(remItem);

		
		
		//setup the action item click listener
		mQuickAction.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
			@Override
			public void onItemClick(QuickAction quickAction, int pos, int actionId) {
				ActionItem actionItem = quickAction.getActionItem(pos);
				
				switch (actionId) {
				case ADD_10:
					selected.setCount(selected.getCount()+ADD_10);
					break;	
				case ADD_100:
					selected.setCount(selected.getCount()+ADD_100);
					break;
				case ADD_1000:
					selected.setCount(selected.getCount()+ADD_1000);
					break;
				case REM_10:
					selected.setCount(selected.getCount()+REM_10);
					break;	
				case REM_100:
					selected.setCount(selected.getCount()+REM_100);
					break;
				case REM_1000:
					selected.setCount(selected.getCount()+REM_1000);
					break;
				case REM_ALL:
					selected.setCount(0);
					quickAction.dismiss();
					break;
				case REM_ITEM:
					delItem(grp,id);
					quickAction.dismiss();
					break;
				default:
					break;
				}
				
				if (selected.getCount()>0){
		        	String[] mystr=context.getResources().getStringArray(R.array.item_type);
		        	String type=mystr[selected.getType()];
		        	String str=String.format("%s  (%d %s)",selected.getName(),selected.getCount(),type);
		        	curenView.setText(str);
		        	
		        }
		        else{
		        	curenView.setText(selected.getName());
		        }
		        	
			}
		});
		
		mQuickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
			@Override
			public void onDismiss() {
				
			}
		});
		
	mQuickAction.show(view);

}
    
    private void delGrp(final int grp){
    	
    	
    	dbOpenHelper.removeGrpFromFav(categorys.get(grp));

    	List<ShopItemData[]> tmpData = new ArrayList<ShopItemData[]>();
    	  
      	  for (int i=0;i<categorys.size();i++){
      		if (i!=grp){		
      		  tmpData.add(data[i]);
      	   }   
      	 }
      	  
        data=null;
        data=new ShopItemData[tmpData.size()][];
      	tmpData.toArray(data);
    	
      	categorys=dbOpenHelper.getFavsCat();
      	
    	notifyDataSetChanged();
    }
    
    private void delItem(final int grp, final int id){
    	
    	Log.v("REM", String.valueOf(grp));
    	List<ShopItemData> tItems = new ArrayList<ShopItemData>();

    	for (int i = 0; i < data[grp].length; i++) {
    	    if (i != id) {
    	    	tItems.add(data[grp][i]);
    	    }
    	    else{
    	    	dbOpenHelper.removeItemFromFav(data[grp][i]);
    	    }
    	}
    	data[grp]=new ShopItemData[tItems.size()];
    	tItems.toArray(data[grp]);
    	
    	notifyDataSetChanged();
    }
    
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        View v = convertView;
        final int grp=groupPosition;
        final int id=childPosition;
        final ShopItemData child = getChild(groupPosition, childPosition);
        
        
        if (child != null) {
            v = vi.inflate(CHILD_ITEM_RESOURCE, null);
            final ViewHolder holder = new ViewHolder(v);
            
         
	        if (child.getCount()>0){
	        	String[] mystr=context.getResources().getStringArray(R.array.item_type);
	        	String type=mystr[child.getType()];
	        	String str=String.format("%s  (%d %s)",child.getName(),child.getCount(),type);
	        	 holder.text.setText(str);
	        	
	        }
	        else{
	        	holder.text.setText(child.getName());
	        	
	        	holder.text.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						QuickActions(child,arg0,grp,id);
					}
				});
	        	
	        	 Button tmpRemButt=(Button)v.findViewById(R.id.remButton);
	             tmpRemButt.setOnTouchListener(new RepeatListener(200, 200, new RepeatButtonClickListener() {
	           	  @Override
	           	  public void onClick(int val) {
	           	    // the code to execute repeatedly
	           		  child.setCount(child.getCount()-val);
	                  if (child.getCount()>0){
	      	        	String[] mystr=context.getResources().getStringArray(R.array.item_type);
	      	        	String type=mystr[child.getType()];
	      	        	String str=String.format("%s  (%d %s)",child.getName(),child.getCount(),type);
	      	        	 holder.text.setText(str);
	      	        	
	      	        }
	                else {    
		      	        	 holder.text.setText(child.getName());
		      	        	
		      	        }
	           	  }
	           	}));
	             
	             
	             
	             Button tmpAddButt=(Button)v.findViewById(R.id.addButton);
	             tmpAddButt.setOnTouchListener(new RepeatListener(200, 200, new RepeatButtonClickListener() {
	             	  @Override
	             	  public void onClick(int val) {
	             	    // the code to execute repeatedly
	             		  child.setCount(child.getCount()+val);
	             	        if (child.getCount()>0){
	            	        	String[] mystr=context.getResources().getStringArray(R.array.item_type);
	            	        	String type=mystr[child.getType()];
	            	        	String str=String.format("%s  (%d %s)",child.getName(),child.getCount(),type);
	            	        	 holder.text.setText(str);
	            	        	
	            	        }
	             	       else {    
			      	        	 holder.text.setText(child.getName());
			      	        	
			      	        }
	             	  }
	             	}));
	        }
           
	   
	        
            
           
           
        }
        return v;
    }

    public String getGroup(int groupPosition) {
        return "group-" + groupPosition;
    }

    public int getGroupCount() {
        return data.length;
    }


    public long getGroupId(int groupPosition) {
        return groupPosition;
    }


    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        View v = convertView;
        String group = null;
        final int group_id = (int)getGroupId(groupPosition);
       // String[] mGroupsNames=categorys.toArray();
        
      
        if (group_id>=0 && group_id<categorys.size())
        {
        	Log.v("GRP", categorys.get(group_id));
            if (categorys.get(group_id) != null) {
                v = vi.inflate(GROUP_ITEM_RESOURCE, null);
                
                TextView tv=(TextView)v.findViewById(R.id.fav_item);
                tv.setText(categorys.get(group_id));
                tv.setOnLongClickListener(new OnLongClickListener() {
    				
    				@Override
    				public boolean onLongClick(View arg0) {
    					// TODO Auto-generated method stub
    					QuickActionsGrp(arg0, group_id);
    					return false;
    				}
    			});
        }
  
        }
        return v;
    }

    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }


    public boolean hasStableIds() {
        return true;
    }
} 